package jgl.vajra.operator.part.home.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

import jgl.vajra.operator.R;
import jgl.vajra.operator.bean.AddressBean;
import jgl.vajra.operator.databinding.ActivityCityPickerBinding;
import jgl.vajra.operator.event.CityPickerEvent;
import jgl.vajra.operator.part.home.viewModel.CityPickerViewModel;
import jgl.vajra.operator.view.city.AreasBean;
import jgl.vajra.operator.view.city.City;
import jgl.vajra.operator.view.city.CityListAdapter;
import jgl.vajra.operator.view.city.CityPickerBean;
import jgl.vajra.operator.view.city.GsonUtil;
import jgl.vajra.operator.view.city.LocateState;
import jgl.vajra.operator.view.city.PinyinUtils;
import jgl.vajra.operator.view.city.ReadAssetsFileUtil;
import jgl.vajra.operator.widget.manager.SPManager;
import jgl.vajra.operator.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.operator.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.operator.widget.permissions.PermissionListener;
import jgl.vajra.operator.widget.permissions.PermissionsUtil;
import jgl.vajra.operator.widget.utils.ToastUtils;

/**
 * 暂时不用,带索引的城市选择去
 */
@CreateViewModel(CityPickerViewModel.class)
public class CityPickerActivity extends BaseMVVMActivity<CityPickerViewModel, ActivityCityPickerBinding> {

    private CityListAdapter mCityAdapter;



    @Override
    public int getLayoutId() {
        return R.layout.activity_city_picker;
    }

    @Override
    public void initView() {
        super.initView();

        mBinding.toolbar.setNavigationIcon(R.drawable.ic_left_arrow);
        mBinding.toolbar.setNavigationOnClickListener(view -> finish());


        mBinding.sideLetterBar.setOverlay(mBinding.tvLetterOverlay);
        mBinding.sideLetterBar.setOnLetterChangedListener(letter -> {
            int position = mCityAdapter.getLetterPosition(letter);
            mBinding.listviewAllCity.setSelection(position);
        });
        mCityAdapter = new CityListAdapter(this);
        mBinding.listviewAllCity.setAdapter(mCityAdapter);

        //子线程中刷新数据
        /*Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) {
                getCityData();
            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new CommonObserver() {

        });*/
        getCityData();

        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {//选择城市
                EventBus.getDefault().post(new CityPickerEvent(name));
                finish();
            }

            @Override
            public void onLocateClick() {//点击定位按钮
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                initLocation();//重新定位
            }
        });

        initLocation();
    }

    private void initLocation(){
        String[] permissions = {
                Manifest.permission.ACCESS_FINE_LOCATION,

        };
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        initLocationManager(CityPickerActivity.this);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        //  ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, permissions, false, null
        );
    }

    private void initLocationManager(Context context) {
        //使用定位管理者获取定位坐标
        LocationManager systemService = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = systemService.getProviders(true);
        String provider = "";
        for (int i = 0; i < providers.size(); i++) {
            if (providers.contains(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
            } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                ToastUtils.showShort("定位失败!");
                mCityAdapter.updateLocateState(LocateState.FAILED, null);
            }
        }
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (TextUtils.isEmpty(provider)) {
            ToastUtils.showShort("检查权限是否开启");
            mCityAdapter.updateLocateState(LocateState.FAILED, null);
        } else {
            Location location = systemService.getLastKnownLocation(provider);
            if (location != null) {
                Logger.d("定位1  " + location.getLatitude() + "---" + location.getLongitude() + "--");
                getAddress(context, location.getLatitude(), location.getLongitude());
            }else {
                mCityAdapter.updateLocateState(LocateState.FAILED, null);
            }
            systemService.requestLocationUpdates(provider, 600000, 1, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                }
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            });
        }

      /*  //获取地理位置管理器
        LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        uploadLocationInfo(bestLocation);
        Logger.d("initLocationManager" + bestLocation.getLatitude() + "----" + bestLocation.getLongitude());*/
    }

    private void getAddress(Context context, double latitude, double longitude) {
        //Geocoder通过经纬度获取具体信息
        Geocoder gc = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> locationList = gc.getFromLocation(latitude, longitude, 1);

            if (locationList != null) {
                Address address = locationList.get(0);
                String countryName = address.getCountryName();//国家
                String countryCode = address.getCountryCode();
                String adminArea = address.getAdminArea();//省
                String locality = address.getLocality();//市
                String subLocality = address.getSubLocality();//区
                String featureName = address.getFeatureName();//街道
                double latitudeAddress = address.getLatitude();
                double longitudeAddress = address.getLongitude();

                AddressBean data=new AddressBean();
                data.countryName=countryName;
                data.countryCode=countryCode;
                data.adminArea=adminArea;
                data.adminArea=adminArea;
                data.locality=locality;
                data.subLocality=subLocality;
                data.featureName=featureName;
                data.latitude=latitudeAddress;
                data.longitude=longitudeAddress;

                mCityAdapter.updateLocateState(LocateState.SUCCESS, locality.replace("市", ""));
                SPManager.HomeData.saveAddressData(data);

                Logger.d("countryName" + countryName + "countryCode" + countryCode + "adminArea" + adminArea
                        + "locality" + locality + "subLocality" + subLocality + "featureName" + featureName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getCityData() {
        String json = ReadAssetsFileUtil.getJson(this, "city.json");
        CityPickerBean bean = GsonUtil.getBean(json, CityPickerBean.class);
        HashSet<City> citys = new HashSet<>();
        for (AreasBean areasBean : bean.data.areas) {
            String name = areasBean.name.replace("　", "");
            citys.add(new City(areasBean.id, name, PinyinUtils.getPinYin(name), areasBean.is_hot == 1));
            for (AreasBean.ChildrenBeanX childrenBeanX : areasBean.children) {
                citys.add(new City(childrenBeanX.id, childrenBeanX.name, PinyinUtils.getPinYin(childrenBeanX.name), childrenBeanX.is_hot == 1));
            }
        }
        //set转换list
        ArrayList<City> cities = new ArrayList<>(citys);
        //按照字母排序
        Collections.sort(cities, new Comparator<City>() {
            @Override
            public int compare(City city, City t1) {
                return city.getPinyin().compareTo(t1.getPinyin());
            }
        });
        mCityAdapter.setData(cities);
    }


    @Override
    public void initData() {
        super.initData();
    }
}
